package com.sry.blog.sys.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.sry.blog.sys.model.Article;
import com.sry.blog.sys.service.ArticleService;
import com.sry.blog.sys.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${file.path}")
    private String MARKDOWN_PATH;

    @Value("${file.path}")
    private String FILE_PATH;

    @Autowired
    private ArticleService articleService;

    @Override
    public String upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            log.error("上传文件为空！");
            throw new RuntimeException("请选择图片");
        }
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
//        /**
//         * 文件UUID的生成规则“文件名-yyyy-MM-dd-随机数”
//         */
//        String fileType = MimeTypeUtils.getExtension(file.getContentType());
//        System.out.println("fileType:" + fileType);
//        String uuidName = HexUtil.encodeHexStr(StrUtil.removeSuffix(fileName, "." + fileType))
//                + "-" + DateUtil.today()
//                + "-" + HexUtil.encodeHexStr(StrUtil.toString(RandomUtil.randomInt(10000)));
//        System.out.println("uuidName:" + uuidName);
//        File newFile = new File(FILE_PATH + UUID.fromString(uuidName).toString(true) + "." + fileType);
        File newFile = new File(FILE_PATH + UUID.fastUUID().toString(true) + fileType);
        file.transferTo(newFile);
        log.info("上传文件：{}", newFile.getName());
        return newFile.getName();
    }

    /**
     * 上传markdown文档
     *
     * @param markdown
     * @return
     * @throws IOException
     */
    @Override
    public String uploadMarkDown(String markdown, String path) throws IOException {
        if (StrUtil.isNotEmpty(path)) {
            return FileUtil.writeUtf8String(markdown, MARKDOWN_PATH + path).getName();
        } else {
            return FileUtil.writeUtf8String(markdown, MARKDOWN_PATH + UUID.fastUUID().toString(true) + ".md").getName();
        }
    }

    @Override
    public String getMarkDown(Integer id) throws IOException {
        Article oneById = articleService.getOneById(id);
        return FileUtil.readUtf8String(MARKDOWN_PATH + oneById.getContent());
    }

    @Override
    public boolean download(MultipartFile file) {
        return false;
    }


}
